//
//  YYYMainViewController.swift
//  Sina12
//
//  Created by yang on 2017/9/21.
//  Copyright © 2017年 成品家（北京）网络科技有限公司. All rights reserved.
//

import UIKit
import SVProgressHUD

// MARK: 主控制器
class YYYMainViewController: UITabBarController {
    //定时器
    var timer: Timer?
    
    //撰写按钮
    private lazy var composeButton = UIButton(imageStr: "tabbar_compose_icon_add", backgroundImageStr: "compose_button", target: self, action: #selector(composeButtonAction))
   
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册监听者
        NotificationCenter.default.addObserver(self, selector: #selector(userShouldLogin), name: NSNotification.Name(rawValue: UserShouldLoginNotification), object: nil)
        //设置子视图控制器
        setupChildController()
        //设置撰写按钮
        setupComposeButton()
        
        //设置定时器
        setupTimer()
        
        //设置代理
        delegate = self
        
        //设置新特性
        setupNewFeature()
    }
    
    @objc private func userShouldLogin(n: Notification)
    {
        var when = DispatchTime.now()
        if n.object != nil
        {
            when = DispatchTime.now() + 2
            //设置加载提示的样式
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "登录超时，请重新登录")
        }
        DispatchQueue.main.asyncAfter(deadline: when ) {
            //展现授权界面
            let navVC = UINavigationController(rootViewController: YYYLoginViewController())
            self.present(navVC, animated: true, completion: nil)
            //恢复样式
            SVProgressHUD.setDefaultMaskType(.clear)
        }
    }
    
    //撰写按钮事件
    @objc private func composeButtonAction()
    {
        // FIXME: 判断用户登陆
        let composeView = YYYComposeView(frame: kMainScreenBounds)
        UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(composeView)
    }
    
    //设置设备支持的方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask
    {
        return .portrait
    }
    
    //销毁定时器
    deinit {
        timer?.invalidate()
    }
}
// MARK: UITabBarControllerDelegate代理方法
extension YYYMainViewController: UITabBarControllerDelegate
{
    /// 将要选择的tabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: 分栏控制器
    ///   - viewController: 目标控制器
    /// - Returns: 是否做切换到目标控制器的操作
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool
    {
        let currentIndex = (childViewControllers as NSArray).index(of: viewController)
    
        if selectedIndex == 0 && currentIndex == selectedIndex
        {
            let navVC = childViewControllers[0] as! YYYNavigationController
            let vc = navVC.childViewControllers[0] as! YYYHomeController

            //设置滚动偏移量
            vc.baseTableView.setContentOffset(CGPoint(x: 0, y: -120), animated: true)
            
            //延迟2s刷新表视图
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: {
                vc.loadData()
            })
            //清除badgeValue、applicationIconBadgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        //isMember 判断是否是某个类，但不是它的子类
        return !viewController.isMember(of: UIViewController.self)
    }
}
// MARK: 设置定时器
extension YYYMainViewController
{
    //定义定时器
    func setupTimer()
    {
        timer = Timer.scheduledTimer(timeInterval: 2000.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc private func updateTimer()
    {
        if !YYYNetworkManager.shared.userLoginOn
        {
            return
        }
        //未读微博的数量
        YYYNetworkManager.shared.unreadStatusData { (count) in
            
            print("未读微博的数量：\(count)条")
            
            //设置首页底部分栏的数量
            self.tabBar.items?[0].badgeValue = (count > 0) ? "\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}
// MARK: 设置界面
extension YYYMainViewController
{
    // MARK: 撰写按钮
    private func setupComposeButton()
    {
        //添加撰写按钮
        tabBar.addSubview(composeButton)
        //设置按钮位置
        let count = CGFloat(childViewControllers.count)
        let width = tabBar.bounds.width/count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: width, dy: 0)
    }
    //MARK: 设置子视图控制器
    private func setupChildController()
    {
        //本地bundle路径
        //从Bundle加载json
        //确定路径、转换为NSData、反序列化
        guard let bundlePath = Bundle.main.path(forResource: "main.json", ofType: nil),
              let bundleData = NSData(contentsOfFile: bundlePath),
        let array = try? JSONSerialization.jsonObject(with: bundleData as Data, options: []) as? [[String: Any]] else
        {
            return
        }
        
        //沙盒路径
        let filePath = (kDocumentPath as NSString).appendingPathComponent("main.json")
        //写入本地沙盒
        bundleData.write(toFile: filePath, atomically: true)

        var arrayVC = [UIViewController]()
   
        for dict in array!
        {
            arrayVC.append(controller(dict: dict))
        }
        //设置视图控制器
        viewControllers = arrayVC
    }
    

    
    //根据字典取值
    private func controller(dict: [String: Any]) -> UIViewController
    {
  
        /*
  
         */
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let vc = NSClassFromString(Bundle.main.namespace + "." + clsName) as? YYYBaseViewController.Type,
            let visitorDict = dict["visitorDict"] as? [String: String]
            else
        {
            return UIViewController()
        }
        //实例化控制器
        let controller = vc.init()
        
        //设置访客视图字典
        controller.visitorDictionary = visitorDict
        controller.title = title
        //分栏图片
        controller.tabBarItem.image = UIImage(named: imageName)
        controller.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
//        controller.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
//        controller.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //分栏字体大小和颜色(系统默认是12号字体)
        controller.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)], for: .normal)
       
   
       //20 82 184
        controller.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.RGBColor(red: 20, green: 82, blue: 184)], for: .selected)
        //设置根视图控制器
        let navVC = YYYNavigationController(rootViewController: controller)
        return navVC
    }
}

extension YYYMainViewController
{
    //设置新特性
    private func setupNewFeature()
    {
        //判断用户是否登录
        if !YYYNetworkManager.shared.userLoginOn
        {
            return
        }
        //检查版本，有新版本显示新特性界面，否则显示欢迎界面
        let newView = isNewVersion ? YYYNewFeatureView(frame: kMainScreenBounds) : YYYWelcomeView(frame: kMainScreenBounds)
        newView.frame = view.bounds
        view.addSubview(newView)
        
    }
    //计算型属性,不分配内存空间
    //extension中可以定义计算型属性
    //构造函数分配存储空间
    /*版本号：主版本号.次版本号.修订版本号
     在AppStore每次升级应用程序，版本号都需要做相应的变化。
     */
    
    // MARK: 检测当前版本和沙盒版本是否一致
    private var isNewVersion: Bool
    {
        //获取当前版本
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        //取出沙盒中的版本
        let fileName = "version"
        //沙盒路径
        let documentPath = (kDocumentPath as NSString).appendingPathComponent(fileName)
        let documentVersion = (try? String(contentsOfFile: documentPath)) ?? ""
        //将当前版本存储到沙盒
        try? currentVersion.write(toFile: documentPath, atomically: true, encoding: .utf8)
        
        return currentVersion != documentVersion
    }
    
}
